package com.rabc.framework.web.service;

import com.exception.base.BaseException;
import com.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class SysLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录业务处理
     * <p>具体的逻辑
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @Verviosn
     */
    public String login(String username, String password, String code) {

        try {
            //使用认证管理器进行认证
            Authentication authentication = null;
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password));

            // 将认证信息存储到安全上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {

            if (e instanceof BadCredentialsException){
                log.error("登陆失败 原因：{} 错误代码{}",e.getCause());
                throw new BadCredentialsException("登录失败");
            }else {
                log.error("登陆失败 原因：{}",e.getCause());
                throw new BaseException(405,"登录失败");
            }
        } finally {
          //  AuthenticationContextHolder.clearContext();
        }


        //生成TOKEN
        return JWTUtil.generateToken(username);
    }
}
